package cn.wolfcode.crm.service.impl;


import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author		12900
 * @time		2018年6月19日下午12:49:54
 * @email		12900qq.com
 * @description 
 */
@Service
public class RoleServiceImpl implements IRoleService {
	@Autowired
	private RoleMapper mapper;
	@Override
	public void save(Role r) {
		mapper.insert(r);
		List<Permission> permissions = r.getPermissions();
		if (permissions != null) {
			for (Permission permission : permissions) {
				mapper.saveRolePermissionRelation(r.getId(), permission.getId());
			}
		}
	}

	@Override
	public void update(Role r) {
		mapper.updateByPrimaryKey(r);
		mapper.deleteRolePermissionRelation(r.getId());
        List<Permission> permissions = r.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                mapper.saveRolePermissionRelation(r.getId(), permission.getId());
            }
        }
	}

	@Override
	public void delete(long id) {
		mapper.deleteRolePermissionRelation(id);
		mapper.deleteByPrimaryKey(id);

	}

	@Override
	public Role get(long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Role> list() {
		return mapper.selectAll();
	}

	@Override
	public PageResult query(QueryObject qo) {
		int total = mapper.queryForCount(qo);
		if (total == 0) {
			return new PageResult();
		}
		List<Role> list = mapper.queryForList(qo);
		return new PageResult(total, list);
	}

	public List<Long> getRoleIdByEmpId(Long empId) {

		return mapper.getRoleIdByEmpId(empId);
	}

	public List<Role> selectByEmpId(Long id) {
		return mapper.selectByEmpId(id);
	}
}
